﻿using ConfExpert.Forms.Aksesuar;
using ConfExpert.Forms.Base;
using ConfExpert.Forms.Depo.Aksesuar;
using ConfExpert.Utility;
using DevExpress.Utils;
using DevExpress.XtraBars;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevTeam;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo
{
    public partial class AksesuarUrunAgaci : XForm
    {
        public AksesuarUrunAgaci()
        {
            InitializeComponent();
        }
        public AksesuarUrunAgaci(int PlanlamaId)
            : this()
        {
            this.PlanlamaId = PlanlamaId;
        }
        public int PlanlamaId { get; set; }
        public int PrdTreeId { get; set; }
        DataTable dtModels;
        private void AksesuarUrunAgaci_Load(object sender, EventArgs e)
        {
            BindingSource bsTree, bsTreeLines, bsModel;
            TAM.PrdTreeTableAdapter = new Datasets.MyDataTableAdapters.PrdTreeTableAdapter();
            TAM.PrdTreeLinesTableAdapter = new Datasets.MyDataTableAdapters.PrdTreeLinesTableAdapter();
            TAM.ModelOfPrdTreeTableAdapter = new Datasets.MyDataTableAdapters.ModelOfPrdTreeTableAdapter();

            dtModels = new DataTable();
            dtModels.Columns.Add("PrdTreeId", typeof(int));
            dtModels.Columns.Add("Models", typeof(string));
            ds.Tables.Add(dtModels);

            //Foreign Key Oluşturma
            DataRelation PrdTree_Model_PrdTreeId = new DataRelation("PrdTree_Model_PrdTreeId",
              ds.PrdTree.Columns["PrdTreeId"],
              dtModels.Columns["PrdTreeId"]);
            ds.Relations.Add(PrdTree_Model_PrdTreeId);
            
            GetDetails("PrdTree;PrdTreeLines;ModelOfPrdTree", "GetPrdTreesByUser", WhoAmI);
            FillModelTable();
            
            ds.PrdTree.Columns.Add("Modeller", typeof(string), "Max(Child(PrdTree_Model_PrdTreeId).Models)");

            bsTree = new BindingSource(ds, "PrdTree");
            bsTreeLines = new BindingSource(bsTree, "FK_PrdTreeLines_PrdTree_PrdTreeId");
            bsModel = new BindingSource(bsTree, "FK_ModelOfPrdTree_PrdTree_PrdTreeId");

            AddBsToList(bsTree, bsTreeLines,bsModel);

            InitGridView(gvMyTrees, bsTree);
            InitGridView(gvMyTreeLines, bsTreeLines);
            InitGridView(gvModel, bsModel);

            gvMyTreeLines.YanYanaGetir("Seri:Qty");
            gvMyTrees.Columns["BrandId"].VisibleIndex = gvMyTrees.Columns["Aciklama"].VisibleIndex;
            gvMyTrees.Columns["Modeller"].VisibleIndex = gvMyTrees.Columns["Aciklama"].VisibleIndex;
            gvMyTrees.MakeColumnInvisible("Name", "InsertedOn");
            gvMyTreeLines.MakeColumnInvisible("PrdTreeId", "PrdTreeLinesId", "IsRelatedofArt", "InsertedOn", "Kategori");
            gvModel.MakeColumnInvisible("PrdTreeId", "ModelOfPrdTreeId");
            gvMyTrees.MakeEditable("Modeller");

            gvMyTreeLines.Columns["Qty"].Caption = "Adet";
            gvMyTreeLines.Columns["Qty"].DisplayFormat.FormatString = "#,##0.###";

            gvMyTreeLines.OptionsView.NewItemRowPosition = gvMyTrees.OptionsView.NewItemRowPosition = gvModel.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
            gvMyTreeLines.BestFitColumns();
            gvMyTrees.BestFitColumns();
            gvMyTrees.Columns["Modeller"].Width = 100;
            gvMyTrees.Columns["Name"].Width = 100;

            GridManager gm = GridManager.GetManager(gvMyTreeLines);
            //gm.GridMenu.AddMenu("Seri Oluştur- tip1", SeriOlustur1);
            //gm.GridMenu.AddMenu("Seri Oluştur- tip2", SeriOlustur2);
            gm.GridMenu.AddMenu("Seriyi Düzenle", SeriyiDuzenle);
            gm.GridMenu.AddMenu("Toplu Resim Göster", Buyut);

            List<string> models = new List<string>();
            foreach (DataRow dr in ds.Tables["Table3"].Rows)
                models.Add(dr["Style"].ToString());

            RepositoryItemComboBox riModel = new RepositoryItemComboBox();
            riModel.Items.AddRange(models);
            riModel.TextEditStyle = TextEditStyles.DisableTextEditor;
            gvModel.Columns["Model"].ColumnEdit = riModel;

            riQty = new RepositoryItemTextEdit();
            riQty.Mask.EditMask = "[2,4]";
            riQty.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;

            if (PlanlamaId > -1)
                gvMyTrees.DoubleClick +=gvMyTrees_DoubleClick;

            emptyEditor = new RepositoryItemButtonEdit();
            emptyEditor.Buttons.Clear();
            emptyEditor.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.HideTextEditor;
            gcMyTreeLines.RepositoryItems.Add(emptyEditor);

            gvMyTreeLines.CustomRowCellEdit += gvMyTreeLines_CustomRowCellEdit;
            gvMyTreeLines.RowCellStyle += gvMyTreeLines_RowCellStyle;
            gvMyTreeLines.CellValueChanged += gvMyTreeLines_CellValueChanged;
            bbiKaydet.ItemClick += btnSave_ItemClick;
            bbiAksesuarEkle.ItemClick += bbiAksesuarEkle_ItemClick;
            bbiRefresh.ItemClick += bbiRefresh_ItemClick;
            gvMyTrees.RowStyle += gvMyTrees_RowStyle;
            ds.PrdTree.TableNewRow += PrdTree_TableNewRow;
            gm.Pasting += gm_Pasting;
            gvMyTreeLines.ShowingEditor += gvMyTreeLines_ShowingEditor;
            gvMyTrees.FocusedRowChanged += gvMyTrees_FocusedRowChanged;
            this.Shown += AksesuarUrunAgaci_Shown;
            splitContainerControl2.SplitterPositionChanged += splitContainerControl2_SplitterPositionChanged;
            splitContainerControl1.SplitterPositionChanged += splitContainerControl1_SplitterPositionChanged;

            DevExpress.Skins.Skin GridSkin = DevExpress.Skins.GridSkins.GetSkin(this.LookAndFeel.ActiveLookAndFeel);
            DevExpress.Skins.SkinElement EvenRowSkin = GridSkin[DevExpress.Skins.GridSkins.SkinGridEvenRow];
            DevExpress.Skins.SkinElement OddRowSkin = GridSkin[DevExpress.Skins.GridSkins.SkinGridOddRow];
            //oddColour = OddRowSkin.Color.BackColor;
            oddColour = EvenRowSkin.Color.BackColor;

            gvMyTrees.SetAlternateRowStyle(false);
            gm.RowDeleteDisabled = false;
            gvModel.GetManager().RowDeleteDisabled = false;

            RefresfBoxes();            
        }

        void AksesuarUrunAgaci_Shown(object sender, EventArgs e)
        {
            splitContainerControl2.SplitterPosition = Convert.ToInt32((splitContainerControl2.Horizontal ? splitContainerControl2.Width : splitContainerControl2.Height) * 0.3);
        }

        void splitContainerControl1_SplitterPositionChanged(object sender, EventArgs e)
        {
            splitContainerControl1.SplitterPosition = this.Size.Width - 150 - splitContainerControl2.SplitterPosition;   
        }

        void splitContainerControl2_SplitterPositionChanged(object sender, EventArgs e)
        {
            splitContainerControl1.SplitterPosition = this.Size.Width - 150 - splitContainerControl2.SplitterPosition;   
        }

        void gvMyTrees_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0)
                return;
            RefresfBoxes();
        }
        private void RefresfBoxes()
        {
            panelControl1.Controls.Clear();

            Label lbBaslik = new Label();
            lbBaslik.Font = new System.Drawing.Font("Calibri", 11F, System.Drawing.FontStyle.Bold);
            lbBaslik.Location = new System.Drawing.Point(1, 5);
            lbBaslik.Size = new Size(lbBaslik.Size.Width + 10, lbBaslik.Size.Height);
            lbBaslik.Text = "EksikKategoriler";
            panelControl1.Controls.Add(lbBaslik);

            DataTable dtZorunlu = ds.Tables["Table5"];
            int boxIndex = 0;
            foreach (DataRow drCategory in dtZorunlu.Rows)
            {
                int PrdTreeId = gvMyTrees.GetFocusedRowCellValue("PrdTreeId").ToInt();
                int ProductCategoryId = drCategory["ProductCategoryId"].ToInt();
                bool IsCatVisible = ds.PrdTreeLines.Select("Kategori = " + ProductCategoryId + " and PrdTreeId = " + PrdTreeId).Length == 0;

                if (IsCatVisible)
                {
                    Label lbl = new Label();
                    panelControl1.Controls.Add(lbl);

                    int y = boxIndex * lbl.Height + 10 + lblBaslik.Height;

                    lbl.Text = drCategory["Name"].ToStr();
                    lbl.Location = new Point(1, y);
                    boxIndex++;
                }
            }
        }

        void bbiRefresh_ItemClick(object sender, ItemClickEventArgs e)
        {
            gvMyTrees.EndEditing();
            gvMyTreeLines.EndEditing();
            gvModel.EndEditing();

            ds.Tables["Table3"].Clear();
            ds.Tables["Table4"].Clear();
            ds.Tables["Table5"].Clear();

            if (CheckConflicts())
                if (ds.HasChanges())
                {
                    dtModels.Clear();
                    Save();
                }

            GetDetails("PrdTree;PrdTreeLines;ModelOfPrdTree", "GetPrdTreesByUser", WhoAmI);
            FillModelTable();
        }

        void gm_Pasting(int rowHandle, GridColumn column, object val, CancelEventArgs ce)
        {
            if (rowHandle < 0)
                return;
            if (column.FieldName == "Qty" && val.ToStr()!="")
            {
                int ProductCategoryId = gvMyTreeLines.GetRowCellValue(rowHandle, "ProductCategoryId").ToInt();
                int AksesuarId = gvMyTreeLines.GetRowCellValue(rowHandle, "AksesuarId").ToInt();

                bool IsProductCategoryExist = ds.Tables["Table4"].Select("ProductCategoryId = " + ProductCategoryId).Length > 0;
                bool IsOptionExist = ds.Tables["Table4"].Select("ProductCategoryId = " + ProductCategoryId + " and Isnull(Qty,0) = " + val.ToStr().Replace(",", ".")).Length > 0;

                ce.Cancel = (IsProductCategoryExist && !IsOptionExist) || AksesuarId == 0 ;
            }
        }

        RepositoryItemButtonEdit emptyEditor;
        void gvMyTreeLines_CustomRowCellEdit(object sender, CustomRowCellEditEventArgs e)
        {
            if (e.Column.FieldName == "Seri" &&
                gvMyTreeLines.GetRowCellDisplayText(e.RowHandle, "AksSeriId") == string.Empty)
                e.RepositoryItem = emptyEditor;

            else if (e.Column.FieldName == "Qty")
            {
                DataTable dtZorunluAdet = ds.Tables["Table4"];
                int ProductCategoryId = gvMyTreeLines.GetRowCellValue(e.RowHandle, "ProductCategoryId").ToInt();
                bool IsProductCategoryExist = dtZorunluAdet.Select("ProductCategoryId = " + ProductCategoryId).Length > 0;
                if (IsProductCategoryExist)
                {
                    List<string> adet = new List<string>();
                    foreach (DataRow dr in dtZorunluAdet.Select("ProductCategoryId = " + ProductCategoryId))
                        adet.Add(dr["Qty"].ToDecimal().ToString("#,##0.###"));

                    RepositoryItemComboBox riAdet = new RepositoryItemComboBox();
                    riAdet.Items.AddRange(adet);
                    riAdet.TextEditStyle = TextEditStyles.DisableTextEditor;
                    e.RepositoryItem = riAdet;
                }
            }
            //gvMyTreeLines.GetRowCellDisplayText(e.RowHandle, "ProductCategoryId") == "BALEN")
            //e.RepositoryItem = riQty;
        }

        RepositoryItemTextEdit riQty;
        void gvMyTreeLines_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            GridView view = sender as GridView;

            int AksesuarId = view.GetRowCellValue(view.FocusedRowHandle, "AksesuarId").ToInt();
            e.Cancel = view.FocusedColumn.FieldName == "Qty" && AksesuarId == 0;
        }

        private DataTable FillModelTable()
        {
            DataTable dtDistinctModels = ds.ModelOfPrdTree.DefaultView.ToTable(true, "Model", "PrdTreeId");
            foreach (DataRow dr in ds.PrdTree.Rows)
            {
                int prdTreeId = dr["PrdTreeId"].ToInt(-1);
                string model = "";

                foreach (DataRow drModel in dtDistinctModels.Select("PrdTreeId=" + prdTreeId))
                {

                    if (drModel["Model"].ToStr() != "")
                        model += drModel["Model"].ToStr() + ",";
                }
                dtModels.Rows.Add(prdTreeId, model.RemoveIfEndsWith(","));
            }
            return dtDistinctModels;
        }
        Color oddColour;
       
        void gvMyTrees_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle < 0)
                return;

            if (e.RowHandle == gvMyTrees.FocusedRowHandle)
            {
                e.Appearance.BackColor = Color.SkyBlue;
                return;
            }
            if (e.RowHandle % 2 == 0)
                e.Appearance.BackColor = oddColour;
            else
                e.Appearance.BackColor = Color.White;
        }

        void bbiAksesuarEkle_ItemClick(object sender, ItemClickEventArgs e)
        {
            int PrdTreeId = gvMyTrees.GetFocusedRowCellValue("PrdTreeId").ToInt();
            DataRow[] drPrdTreeLines = ds.PrdTreeLines.Select("PrdTreeId = " + PrdTreeId);
            using (AksesuarSec aks = new AksesuarSec(drPrdTreeLines))
                if (aks.ShowDialog() == DialogResult.OK)
                {
                    DataTable dtAksesuar = aks.DtAksesuar;

                    foreach (DataRow drAksesuar in dtAksesuar.Rows)
                    {
                        int AksesuarId = drAksesuar["AksesuarId"].ToInt();
                        int sProductCategoryId = AppSession.Lookups.V_Aksesuar.FindByAksesuarId(AksesuarId).ProductCategoryId;
                        bool IsAksesuarExist = ds.PrdTreeLines.Select("PrdTreeId = " + PrdTreeId + " and AksesuarId = " + AksesuarId).Length > 0;
                        if (!IsAksesuarExist)
                        {
                            Datasets.MyData.PrdTreeLinesRow dr = ds.PrdTreeLines.NewPrdTreeLinesRow();

                            dr.PrdTreeId = PrdTreeId;
                            dr.AksesuarId = AksesuarId;
                            dr.Qty = Convert.ToDouble(drAksesuar["Adet"]);
                            dr["Kategori"] = sProductCategoryId;

                            ds.PrdTreeLines.AddPrdTreeLinesRow(dr);
                        }
                    }
                    RefresfBoxes();
                    bbiKaydet.PerformClick();
                }
        }

        void gvMyTreeLines_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            int Rowhandle = e.RowHandle;
            if (e.Column.FieldName == "AksesuarId")
            {
                string Balen = gvMyTreeLines.GetRowCellDisplayText(Rowhandle, "ProductCategoryId").ToStr();
                string Aciklama = gvMyTreeLines.GetRowCellDisplayText(Rowhandle, "Aciklama").ToStr();
                int ProductCategoryId = gvMyTreeLines.GetRowCellValue(Rowhandle, "ProductCategoryId").ToInt();
                gvMyTreeLines.SetRowCellValue(Rowhandle, "Kategori", ProductCategoryId);

                if (Balen == "BALEN")
                    if (Aciklama.Contains("İÇTEN"))
                        gvMyTreeLines.SetRowCellValue(Rowhandle, "Qty", 2);
                    else if (Aciklama.Contains("DIŞTAN"))
                        gvMyTreeLines.SetRowCellValue(Rowhandle, "Qty", null);
                gvMyTreeLines.EndEditing();
                RefresfBoxes();
            }
        }

        private void Buyut(object sender, EventArgs e)
        {
            string idxs = gvMyTreeLines.GetSelectedValues("AksesuarId");
            using (Resimler rs = new Resimler(idxs))
                rs.ShowDialog();
        }

        void gvMyTreeLines_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            if (e.Column.FieldName == "Qty")
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Bold);
        }

        private string GetAksesuarIds()
        {
            string idxs = string.Empty;
            foreach (int rowHandle in gvMyTreeLines.GetSelectedRows())
                if (rowHandle > -1)
                    idxs += gvMyTreeLines.GetRowCellValue(rowHandle, "AksesuarId").ToString() + ",";

            idxs = idxs.RemoveIfEndsWith(",");
            return idxs;
        }

        private void SeriOlustur1(object sender, EventArgs e)
        {
            //if (GetTipNull())
            //{
            //    int FRH = gvAna.FocusedRowHandle;
            //    gvAna.VeriyiGuncelle("InsAksSeriler", 1, GetAksesuarIds());
            //    gvAna.MakeRowVisible(FRH);
            //    gvAna.FocusedRowHandle = FRH;

            //    ConfExpert.Forms.Depo.Aksesuar.AksesuarSeri aseri = new ConfExpert.Forms.Depo.Aksesuar.AksesuarSeri((int)gvAna.Dataset().Tables[2].Rows[0][0]);
            //    aseri.ShowDialog();
            //}
            //else
            //    XtraMessageBox.Show("Seçili aksesuarların tamamının SeriId'si boş olmalıdır.");
        }

        private void SeriOlustur2(object sender, EventArgs e)
        {
            //if (GetTipNull())
            //{
            //    int FRH = gvAna.FocusedRowHandle;
            //    gvAna.VeriyiGuncelle("InsAksSeriler", 2, GetAksesuarIds());
            //    gvAna.MakeRowVisible(FRH);
            //    gvAna.FocusedRowHandle = FRH;

            //    AksesuarSeriTip2 aseri = new AksesuarSeriTip2((int)gvAna.Dataset().Tables[2].Rows[0][0]);
            //    aseri.ShowDialog();
            //}
            //else
            //    XtraMessageBox.Show("Seçili aksesuarların tamamının SeriId'si boş olmalıdır.");
        }

        private void SeriyiDuzenle(object sender, EventArgs e)
        {
            int AksSeriId = intParse(gvMyTreeLines.GetFocusedRowCellValue("AksSeriId"));
            if (AksSeriId > 0)
                using (ConfExpert.Forms.Depo.Aksesuar.AksesuarSeri aseri = new ConfExpert.Forms.Depo.Aksesuar.AksesuarSeri(AksSeriId))
                    aseri.ShowDialog();

            //switch (intParse(gvMyTreeLines.GetFocusedRowCellValue("Tip")))    //ÖNEMLİ!
            //{
            //    case 1:
            //        ConfExpert.Forms.Depo.Aksesuar.AksesuarSeri aseri = new ConfExpert.Forms.Depo.Aksesuar.AksesuarSeri(AksSeriId);
            //        aseri.ShowDialog();
            //        break;

            //    case 2:
            //        AksesuarSeriTip2 aseritip2 = new AksesuarSeriTip2(AksSeriId);
            //        aseritip2.ShowDialog();
            //        break;
            //}
        }         
        void gvMyTrees_DoubleClick(object sender, EventArgs e)
        {
            if (gvMyTrees.FocusedRowHandle > -1)
            {
                PrdTreeId = gvMyTrees.GetFocusedRowCellValue( "PrdTreeId").ToInt();
                this.DialogResult = DialogResult.OK;
            }
        }

        void PrdTree_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["UserId"] = WhoAmI;
            RefresfBoxes();
            //int PrdTreeId = e.Row["PrdTreeId"].ToInt();
            //DataRow[] drKategori = ds.Tables["Table4"].Select("IsRequired = 1");
            //foreach (DataRow dr in drKategori)
            //{
            //    Datasets.MyData.PrdTreeLinesRow row = ds.PrdTreeLines.NewPrdTreeLinesRow();
            //    row.PrdTreeId = PrdTreeId;

            //    ds.PrdTreeLines.Rows.Add(row);
            //}
        }

        void btnSave_ItemClick(object sender, ItemClickEventArgs e)
        {
            gvMyTrees.EndEditing();
            gvMyTreeLines.EndEditing();
            gvModel.EndEditing();

            if (CheckConflicts())
                if (ds.HasChanges())
                {
                    dtModels.Clear();
                    Save();
                }

            gvMyTrees.Columns["Modeller"].VisibleIndex = gvMyTrees.Columns["Aciklama"].VisibleIndex;
            FillModelTable();
        }

        bool CheckConflicts()
        {
            //Boş Qty lere izin verme
            DataRow[] drNullQty = ds.PrdTreeLines.Select("Qty is null");
            if (drNullQty.Length > 0)
            {
                string NullQtyHata = "";
                foreach (DataRow dr in drNullQty)
                {
                    if (!NullQtyHata.Contains(dr["PrdTreeId"].ToString()))
                    {
                        NullQtyHata += dr["PrdTreeId"].ToString() + ",";
                    }
                }
                NullQtyHata = NullQtyHata.RemoveIfEndsWith(",");
                ShowErrorMessage(NullQtyHata + " nolu ürün ağaç(lar)ında aksesuar ADETLERİ boş girilmiş aksesuarlar var. Lütfen ADET alanlarını doldurunuz!");
                return false;
            }

            //Boş BrandId lere izin verme
            DataRow[] drBosBrand = ds.PrdTree.Select("BrandId is null");
            if (drBosBrand.Length > 0)
            {
                string BosBrandHata = "";
                foreach (DataRow dr in drBosBrand)
                {
                    BosBrandHata += dr["PrdTreeId"].ToString() + ",";
                }
                BosBrandHata = BosBrandHata.RemoveIfEndsWith(",");
                ShowErrorMessage(BosBrandHata + " nolu ürün ağaç(lar)ının MARKA alanları boş bırakılmış. Lütfen BrandId alanlarını doldurunuz!");
                return false;
            }

            DataTable dt = new DataTable();
            dt.Columns.Add("AksesuarId");
            dt.Columns.Add("PrdTreeId");
            dt.Columns.Add("Adet");

            //Aynı aksesuardan birden fazla tanıtılmış ürün ağaçlarının kontrolü
            DataTable dtAksesuar = ds.PrdTreeLines.Select("PrdTreeLinesId is not null").CopyToDataTable();

            var qrCiftAksesuar = from item in dtAksesuar.AsEnumerable()
                                 group item by new { AksesuarId = item.Field<int>("AksesuarId"), PrdTreeId = item.Field<int>("PrdTreeId") }
                                     into grp
                                     select new
                                     {
                                         AksesuarId = grp.Key.AksesuarId,
                                         PrdTreeId = grp.Key.PrdTreeId,
                                         Adet = grp.Count(),
                                     };

            foreach (var item in qrCiftAksesuar)
            {
                dt.Rows.Add(item.AksesuarId, item.PrdTreeId, item.Adet);
            }

            DataRow[] drCift = dt.Select("Adet>1");
            if (drCift.Length > 0)
            {
                string ciftAksesuar = "";
                foreach (DataRow dr in drCift)
                {
                    ciftAksesuar += dr["PrdTreeId"].ToString() + ",";
                }
                ciftAksesuar = ciftAksesuar.RemoveIfEndsWith(",");
                ShowErrorMessage(ciftAksesuar + " nolu ürün ağaç(lar)ında aynı AKSESUARDAN ikişer kere girilmiş. Lütfen çift kayıtları düzelttikten sonra kaydediniz!");
                return false;
                //gvMyTrees.RowCellStyle += gvMyTrees_RowCellStyle;
            }

            //Aynı seriden iki aksesuarı aynı ürün ağacında kullanılmasını engellemek
            DataTable dtAyniSeri = new DataTable();
            dtAyniSeri.Columns.Add("AksSeriId");
            dtAyniSeri.Columns.Add("PrdTreeId");
            dtAyniSeri.Columns.Add("Adet");

            DataRow[] drAksesuarLU = AppSession.Lookups.V_Aksesuar.Select("AksSeriId is not null");
            if (drAksesuarLU.Length > 0)
            {
                DataTable dtAksesuarLU = drAksesuarLU.CopyToDataTable();
                DataTable dtAksesuarSeri = ds.PrdTreeLines.Select("PrdTreeLinesId is not null and ISNULL(Seri,0)=1").CopyToDataTable();

                var qrAyniSeri = from item in dtAksesuarSeri.AsEnumerable()
                                 join item2 in dtAksesuarLU.AsEnumerable() on item.Field<int>("AksesuarId") equals item2.Field<int>("AksesuarId")
                                 group item by new { AksSeriId = item2.Field<int>("AksSeriId"), PrdTreeId = item.Field<int>("PrdTreeId") }
                                     into grp
                                     select new
                                     {
                                         AksSeriId = grp.Key.AksSeriId,
                                         PrdTreeId = grp.Key.PrdTreeId,
                                         Adet = grp.Count(),
                                     };

                foreach (var item in qrAyniSeri)
                {
                    if (item.AksSeriId.ToInt() > 0)
                        dtAyniSeri.Rows.Add(item.AksSeriId, item.PrdTreeId, item.Adet);
                }

                DataRow[] drAyniSeri = dtAyniSeri.Select("Adet>1");
                if (drAyniSeri.Length > 0)
                {
                    string ciftSeri = "";
                    foreach (DataRow dr in drAyniSeri)
                    {
                        ciftSeri += dr["PrdTreeId"].ToString() + ",";
                    }
                    ciftSeri = ciftSeri.RemoveIfEndsWith(",");
                    ShowErrorMessage(ciftSeri + " nolu ürün ağaç(lar)ında aynı SERİDEN iki aksesuar kullanılmış. Lütfen kontrol ediniz !");
                    return false;
                }
            }

            //Boş BrandId lere izin verme
            foreach (DataRow drBosSezonId in ds.ModelOfPrdTree.Select("SezonId is null"))
            {
                drBosSezonId["SezonId"] = 0;
            }

            //Aynı modelin aynı brand'e bağlı iki farklı ürün ağacında kullanılmasını engellemek
            DataTable dtAyniModel = new DataTable();
            dtAyniModel.Columns.Add("BrandId");
            dtAyniModel.Columns.Add("Model");
            dtAyniModel.Columns.Add("Adet");
            dtAyniModel.Columns.Add("SezonId");
            dtAyniModel.Columns.Add("TalepTipiId");

            DataTable dtModel = ds.ModelOfPrdTree.Select("ModelOfPrdTreeId is not null").CopyToDataTable();

            var qrAyniModel = from item in ds.PrdTree
                              join item2 in dtModel.AsEnumerable() on item.PrdTreeId equals item2.Field<int>("PrdTreeId")
                              group item by new { item.BrandId, Model = item2.Field<string>("Model"), SezonId = item2.Field<int>("SezonId"), TalepTipiId = item2.Field<int?>("TalepTipiId") }
                                  into grp
                                  select new
                                  {
                                      BrandId = grp.Key.BrandId,
                                      Model = grp.Key.Model,
                                      SezonId = grp.Key.SezonId,
                                      TalepTipiId = grp.Key.TalepTipiId,
                                      Adet = grp.Count(),
                                  };

            foreach (var item in qrAyniModel)
            {
                dtAyniModel.Rows.Add(item.BrandId, item.Model, item.Adet, item.SezonId, item.TalepTipiId);
            }

            DataRow[] drAyniModel = dtAyniModel.Select("Adet>1");
            if (drAyniModel.Length > 0)
            {
                string ciftModel = "";
                foreach (DataRow dr in drAyniModel)
                {
                    ciftModel += dr["Model"].ToString() + ",";
                }
                ciftModel = ciftModel.RemoveIfEndsWith(",");
                ShowErrorMessage(ciftModel + " model(ler)i birden fazla tanımlandı. Lütfen kontrol ediniz !");
                return false;
            }

            return true;

        }
    }
}